package com.lazy.tcp;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;


public class TelnetServer {
    private static Logger logger = Logger.getLogger("TelnetServer");

    private final int port;

    
	/** 用户传入的channelHandler */
	protected ChannelHandler myHandler = null;
	
    protected ServerBootstrap bootstrap = null;

    public TelnetServer(int port, ChannelHandler myHandler) {
        this.port = port;
		this.myHandler = myHandler;
        // Configure the server.
        bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newFixedThreadPool(100),
                        Executors.newFixedThreadPool(100)));
                        // Executors.newCachedThreadPool(),
                        // Executors.newCachedThreadPool()));
    }
    
    public void bind() {
        // Configure the pipeline factory.
//        bootstrap.setPipelineFactory(new TcpNettyServerPipelineFactory(decodeHandler));
        bootstrap.setPipelineFactory(new TelnetServerPipelineFactory(myHandler));

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(port));
    }
    
    public void close() {
        if (bootstrap != null) {
            if (getHandler() != null) {
                TelnetServerHandler handler = (TelnetServerHandler) getHandler();
                if (!handler.getChannels().isEmpty() ) {
                    handler.getChannels().disconnect();
                }
            }

            bootstrap.releaseExternalResources();
            bootstrap = null;
        }
    }
    
    /**
     * 返回处理程序的handler
     * @return
     */
    public ChannelHandler getHandler() {
        return myHandler;
    }


    public void addReceivedListener(IListener listener) {
        if (myHandler != null) {
            ((TelnetServerHandler)myHandler).setReceivedListener(listener);
        }
    }

    /** telnet 处理接口 */
    public static interface IListener {
        public String process(String msg);
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 9102;
        }
        
        
        TelnetServerHandler myHandler = new TelnetServerHandler();
        // myHandler.setReceivedListener(listener);

        new TelnetServer(port, myHandler).bind();
    }

}
